package com.training.killerapp;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.training.killerapp.model.User;

public class LoginServlet extends AbstractKillerAppServlet
{
    protected void doPost( HttpServletRequest request, HttpServletResponse response )
        throws ServletException, IOException
    {
        if( request.getParameter( "logout" ) != null )
        {
            HttpSession session = request.getSession();
            session.setAttribute( "currentUser", null );
            response.sendRedirect( "index.jsp?message=Logged Out" );
        }

        String email = request.getParameter( "email" );
        String password = request.getParameter( "password" );

        KillerApp killerApp = retrieveKillerApp();
        try
        {
            User attemptedUser = killerApp.getUser( email );
            if( attemptedUser == null )
            {
                response.sendRedirect( "index.jsp?message=Account Does Not Exist" );
            }
            else if( password != null && password.equals( attemptedUser.getPassword() ) )
            {
                setCurrentUser( request, attemptedUser );

                response.sendRedirect( "list" );
            }
            else
            {
                response.sendRedirect( "index.jsp?message=Login Failed" );
            }
        }
        finally
        {
            releaseKillerApp( killerApp );
        }
    }

    protected void doGet( HttpServletRequest request, HttpServletResponse response )
        throws ServletException, IOException
    {
        if( request.getParameter( "logout" ) != null )
        {
            HttpSession session = request.getSession();
            session.setAttribute( "currentUser", null );
            response.sendRedirect( "index.jsp?message=Logged Out" );
        }
    }
}
